package com.srwl.mytx.activity;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.media.Ringtone;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.localbroadcastmanager.content.LocalBroadcastManager;

import com.alibaba.fastjson.JSONObject;
import com.srwl.mytx.Constant;
import com.srwl.mytx.Helper;
import com.srwl.mytx.R;
import com.srwl.mytx.RetrofitManager;
import com.srwl.mytx.dao.DBManager;
import com.srwl.mytx.domain.CommonResult;
import com.srwl.mytx.domain.User;
import com.srwl.mytx.service.UserService;
import com.srwl.mytx.utils.ClickUtil;
import com.srwl.mytx.utils.GlideLoadUtils;
import com.starrtc.starrtcsdk.api.XHClient;
import com.starrtc.starrtcsdk.apiInterface.IXHResultCallback;

import butterknife.BindView;
import butterknife.ButterKnife;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class AudioRingingActivity extends BaseActivity implements View.OnClickListener {
    private static final String TAG = "AudioRingingActivity";
    @BindView(R.id.tv_nick)
    TextView tv_nick;
    @BindView(R.id.iv_avatar)
    ImageView iv_avatar;
    @BindView(R.id.tv_status)
    TextView tv_status;
    private String targetId;
    private User targetUser;
    private BroadcastReceiver receiver;
    private LocalBroadcastManager broadcastManager;
    private Ringtone ringtone;
    private boolean cancelled;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);
        //设置不黑屏等
        getWindow().addFlags(
                WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON | WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD
                        | WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED
                        | WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON);
        setContentView(R.layout.activity_audio_chat_ring);
        ButterKnife.bind(this);
        registerBroadcastReceiver();
        targetUser = getIntent().getParcelableExtra("targetUserInfo");
        if (targetUser == null) {
            targetId = getIntent().getStringExtra("userId");
            targetUser = Helper.getInstance().getContactUserInfo(targetId);
            if (targetUser == null) {
                getUserInfo(targetId);
            }
        } else {
            targetId = targetUser.getuId();
        }

        showTargetUserInfo();
        findViewById(R.id.iv_refuse_call).setOnClickListener(this);
        findViewById(R.id.iv_receive).setOnClickListener(this);
        Uri notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_RINGTONE);
        ringtone = RingtoneManager.getRingtone(this, notification);
        ringtone.play();
    }

    private void showTargetUserInfo() {
        if (targetUser == null) {
            return;
        }
        //Glide.with(this).load(targetUser.getAvatar()).error(R.drawable.tx_default_avatar_1).into(iv_avatar);
        GlideLoadUtils.glideLoad(this, targetUser.getAvatar(), iv_avatar, R.drawable.tx_default_avatar_1);
        String username = targetUser.getUsername();
        if (username == null) {
            username = targetUser.getNick();
        }
        tv_nick.setText(username);
    }

    private void registerBroadcastReceiver() {
        broadcastManager = LocalBroadcastManager.getInstance(this);
        IntentFilter filter = new IntentFilter();
        filter.addAction(Constant.ACTION_ON_HANG_UP);
        filter.addAction(Constant.ACTION_ON_CALL_ERROR);
        filter.addAction(Constant.ACTION_ON_HANG_UP);

        receiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                cancelled = true;
                switch (intent.getAction()) {


                    case Constant.ACTION_ON_CALL_CANCEL:
                        Log.d(TAG, "对方语音通话请求已经取消");
                        tv_status.setText("对方已经取消呼叫");
                        postDelayedFinish(1000);
                        break;
                    case Constant.ACTION_ON_CALL_ERROR:
                        tv_status.setText("接通语音通话出错");
                        postDelayedFinish(1000);
                        break;
                    case Constant.ACTION_ON_HANG_UP:
                        Log.d(TAG, "对方已经取消呼叫");
                        tv_status.setText("对方已经取消呼叫");
                        postDelayedFinish(1000);

                        break;
                }
            }
        };
        broadcastManager.registerReceiver(receiver, filter);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        broadcastManager.unregisterReceiver(receiver);
    }

    @Override
    public void onClick(View v) {
        if (cancelled) {
            return;
        }
        if (ClickUtil.isFastClick()) {
            return;
        }
        switch (v.getId()) {
            case R.id.iv_refuse_call:
                ringtone.stop();
                XHClient.getInstance().getVoipManager().refuse(new IXHResultCallback() {
                    @Override
                    public void success(Object data) {
                        finish();
                    }

                    @Override
                    public void failed(String errMsg) {
                        finish();
                    }
                });
                break;
            case R.id.iv_receive: {
                ringtone.stop();
                Intent intent = new Intent(AudioRingingActivity.this, AudioChatActivity.class);
                intent.putExtra("userId", targetId);
                intent.putExtra(AudioChatActivity.ACTION, AudioChatActivity.RING);
                startActivity(intent);
                finish();
                break;
            }
        }
    }


    private void postDelayedFinish(int delayMillis) {
        if (ringtone != null) {
            ringtone.stop();
        }
        Helper.getInstance().setStartingCall(false);
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                finish();
            }
        }, delayMillis);
    }

    private void getUserInfo(String userId) {
        RetrofitManager.getInstance().createRequest(UserService.class)
                .getUserInfo(userId)
                .enqueue(new Callback<CommonResult>() {
                    @Override
                    public void onResponse(Call<CommonResult> call, Response<CommonResult> response) {
                        CommonResult result = response.body();
                        if (!response.isSuccessful() || result == null) {
                            Log.e(TAG, "onResponse:从服务端获取联系人信息出错 " + response.message());
                            return;
                        }

                        if (result.isError()) {
                            Log.e(TAG, "onResponse:从服务端获取联系人信息出错 " + result.getMsg());
                            return;
                        }

                        JSONObject object = (JSONObject) result.getData();

                        User user = object.toJavaObject(User.class);
                        user.setUId(userId);
                        user.setType(Constant.USER_TYPE_TEMP);
                        DBManager.getInstance().getDaoSession().getUserDao().insertOrReplace(user);//作为临时联系人，保存在用户表中
                        targetUser = user;
                        showTargetUserInfo();
                    }

                    @Override
                    public void onFailure(Call<CommonResult> call, Throwable t) {

                        Log.e(TAG, "onFailure: " + t.getMessage());
                    }
                });
    }


}
